// components/accredit/accredit.js
const app = getApp();

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
 * 获取用户手机号授权
 */
    getPhoneNumber: function (e) {
      let that = this;
      let wxUser = wx.getStorageSync('wxUser');
      console.log(e);
      console.log(wxUser);
      let shareUid = wx.getStorageSync('shareUid')
      
      if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '未授权',
          success: function (res) { }
        })
      } else {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '同意授权',
          success: function (res) {
            let wxUserInfo = wxUser.userInfo;
            let param = {
              code: wxUser.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              avatarUrl: wxUserInfo.avatarUrl,
              nickName: wxUserInfo.nickName,
              province: wxUserInfo.province,
              city: wxUserInfo.city,
              country: wxUserInfo.country,
              superiorid: shareUid
            }
            app.request({
              url: app.getApi('login/min_login'),
              data: param,
              success: function (res) {
                console.log(res)
                var obj = {};
                obj.openid = res.user.openid;
                obj.uid = res.user.uid;
                obj.Name = wxUserInfo.nickName;
                obj.avatarUrl = wxUserInfo.avatarUrl;
                console.log(obj);
                wx.setStorageSync('user', obj);//存储openid  

                that.triggerEvent("loginPhone", obj);
              },
              fail:function(error) {
                console.log('授权接口请求失败');
                wx.showModal({
                  title: '授权失败',
                  content: '请重新授权操作',
                  success: function (res) {
                    wx.clearStorageSync();    //清除缓存
                    wx.switchTab({
                      url: '/shop',
                    })
                  }
                })
              }
            });
          },
          fail:function(err) {
            console.log('授权失败');
          }
        })
        
      }
    },
  },

  /**
   * 组件实例化，但节点树还未导入，因此这时不能用setData
   */
  created() {

  },

  /**
   * 节点树完成，可以用setData渲染节点，但无法操作节点
   */
  attached() {
    console.log(app.globalData.noaccredit);
  },

  /**
   * 组件布局完成，这时可以获取节点信息，也可以操作节点
   */
  ready() {

  },
  /**
   * 组件实例被移动到树的另一个位置
   */
  moved() {

  },

  /**
   * 组件实例从节点树中移除
   */
  detached() {

  }
})
